//
//  ATWaveAnimateView.m
//  ATWaveAnimation
//
//  Created by 柳栗斌 on 16/8/6.
//  Copyright © 2016年 柳栗斌. All rights reserved.
//

#define ATDefaultFirstWaveColor [UIColor colorWithRed:34/255.0 green:116/255.0 blue:210/255.0 alpha:1]
#define ATDefaultSecondWaveColor [UIColor colorWithRed:34/255.0 green:116/255.0 blue:210/255.0 alpha:0.3]
#define ATDefaultBorderColor [UIColor colorWithRed:244/255.0 green:244/255.0 blue:248/255.0 alpha:1].CGColor

#import "ATWaveAnimateView.h"
#import "YYWeakProxy.h"

@interface ATWaveAnimateView ()

/**
 * 正弦型函数解析式：y=Asin（ωx+φ）+h
   各常数值对函数图像的影响：
   φ（初相位）：决定波形与X轴位置关系或横向移动距离（左加右减）
   ω：决定周期（最小正周期T=2π/|ω|）
   A：决定峰值（即纵向拉伸压缩的倍数）
   h：表示波形在Y轴的位置关系或纵向移动距离（上加下减）
 */

/**
 * 加入容器高度是100，若希望波的整体高度固定在容器的一个相对的位置。
   如果这里设置h ＝ 30；也就是说，当Asin（ωx+φ）计算为0的时候，这个时候y的位置是30
 */
@property (nonatomic,assign) CGFloat yHeight;

@property (nonatomic,assign) CGFloat offSetX;

/**
 * 计时器
 * CADisplayLink是一个能让我们以和屏幕刷新率相同的频率将内容画到屏幕上的定时器
 * NSTimer不是很精确，而且会出现卡顿的情况
 */
@property (nonatomic,strong) CADisplayLink *displayLinkTimer;

/**
 * 第一个波浪层
 */
@property (nonatomic,strong) CAShapeLayer *firstWaveShapeLayer;

/**
 * 第二个波浪层
 */
@property (nonatomic,strong) CAShapeLayer *secondWaveShapeLayer;

@end


@implementation ATWaveAnimateView

- (instancetype)initWithFrame:(CGRect)frame{
    
    if (self = [super initWithFrame:frame]) {
        
        CGFloat minNum = MIN(frame.size.width, frame.size.height);
        
        self.bounds = CGRectMake(0, 0, minNum, minNum);
        self.layer.cornerRadius = minNum * 0.5;
        self.layer.masksToBounds = YES;
        self.layer.borderColor = ATDefaultBorderColor;
        self.layer.borderWidth = 5.0f;
        
        self.waveHeight = 5.0;
        self.firstWaveColor = ATDefaultFirstWaveColor;
        self.secondWaveColor = ATDefaultSecondWaveColor;
        self.yHeight = self.bounds.size.height;
        self.speed = 1.0;
        
        [self.layer addSublayer:self.firstWaveShapeLayer];
        if (!self.isShowSingleWave) {
            
            [self.layer addSublayer:self.secondWaveShapeLayer];
        }
        
        [self addSubview:self.progressLabel];
    
    }
    
    return self;
}

//重写进度条的set方法
- (void)setProgress:(CGFloat)progress{
    
    _progress = progress;
    
    _progressLabel.text = [NSString stringWithFormat:@"%ld%%",[[NSNumber numberWithFloat:progress * 100] integerValue]];
    _progressLabel.textColor=[UIColor colorWithWhite:progress*1.8 alpha:1];
    self.yHeight = self.bounds.size.height * (1 - progress);
    
    [self stopWaveAnimation];
    [self startWaveAnimation];
}

#pragma mark -- 开始波动动画
- (void)startWaveAnimation
{
    self.displayLinkTimer = [CADisplayLink displayLinkWithTarget:[YYWeakProxy proxyWithTarget:self] selector:@selector(waveAnimation)];
    [self.displayLinkTimer addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
}


#pragma mark -- 停止波动动画
- (void)stopWaveAnimation
{
    
    [self.displayLinkTimer invalidate];
    self.displayLinkTimer = nil;
}

#pragma mark -- 波动动画实现
- (void)waveAnimation
{
    CGFloat waveHeight = self.waveHeight;
    if (self.progress == 0.0f || self.progress == 1.0f) {
        waveHeight = 0.f;
    }
    
    //offSetX决定x位置
    self.offSetX += self.speed;
    
    //声明第一条波曲线的路径
    CGMutablePathRef pathRef1 = CGPathCreateMutable();
    
    CGFloat startOffY1 = waveHeight * sinf(self.offSetX * M_PI * 2 / self.bounds.size.width);
    CGFloat orignOffY1 = 0.0;
    
    //设置起始点
    CGPathMoveToPoint(pathRef1, NULL, 0, startOffY1);
    
    //第一个波纹的公式
    for (CGFloat i = 0.f; i <= self.bounds.size.width; i++) {
        orignOffY1 = waveHeight * sinf(2 * M_PI / self.bounds.size.width * i + self.offSetX * M_PI * 2 / self.bounds.size.width) + self.yHeight;
        CGPathAddLineToPoint(pathRef1, NULL, i, orignOffY1);
    }
    
    //把绘图信息添加到路径里
    CGPathAddLineToPoint(pathRef1, NULL, self.bounds.size.width, orignOffY1);
    CGPathAddLineToPoint(pathRef1, NULL, self.bounds.size.width, self.bounds.size.height);
    CGPathAddLineToPoint(pathRef1, NULL, 0, self.bounds.size.height);
    CGPathAddLineToPoint(pathRef1, NULL, 0, startOffY1);
    
    //结束绘图信息
    CGPathCloseSubpath(pathRef1);
    
    self.firstWaveShapeLayer.path = pathRef1;
    self.firstWaveShapeLayer.fillColor = self.firstWaveColor.CGColor;
    
    //释放绘图路径
    CGPathRelease(pathRef1);
    
    /*
     * 第二个波纹
     */
    if (!self.isShowSingleWave) {
        
        CGMutablePathRef pathRef2 = CGPathCreateMutable();
        
        CGFloat startOffY2 = waveHeight * sinf(self.offSetX * M_PI * 2 / self.bounds.size.width);
        CGFloat orignOffY2 = 0.0;
        CGPathMoveToPoint(pathRef2, NULL, 0, startOffY2);
        
        for (CGFloat i = 0.f; i <= self.bounds.size.width; i++) {
            orignOffY2 = waveHeight * cosf(2 * M_PI / self.bounds.size.width * i + self.offSetX * M_PI * 2 / self.bounds.size.width) + self.yHeight;
            CGPathAddLineToPoint(pathRef2, NULL, i, orignOffY2);
        }
        
        CGPathAddLineToPoint(pathRef2, NULL, self.bounds.size.width, orignOffY2);
        CGPathAddLineToPoint(pathRef2, NULL, self.bounds.size.width, self.bounds.size.height);
        CGPathAddLineToPoint(pathRef2, NULL, 0, self.bounds.size.height);
        CGPathAddLineToPoint(pathRef2, NULL, 0, startOffY2);
        
        CGPathCloseSubpath(pathRef2);
        
        self.secondWaveShapeLayer.path = pathRef2;
        self.secondWaveShapeLayer.fillColor = self.secondWaveColor.CGColor;
        
        CGPathRelease(pathRef2);
    }
    
}

#pragma mark - 懒加载方法
- (CAShapeLayer *)firstWaveShapeLayer{
    
    if (!_firstWaveShapeLayer) {
        
        _firstWaveShapeLayer = [CAShapeLayer layer];
        _firstWaveShapeLayer.frame = self.bounds;
        _firstWaveShapeLayer.fillColor = _firstWaveColor.CGColor;
    }
    
    return _firstWaveShapeLayer;
}

- (CAShapeLayer *)secondWaveShapeLayer{
    
    if (!_secondWaveShapeLayer) {
        
        _secondWaveShapeLayer = [CAShapeLayer layer];
        _secondWaveShapeLayer.frame = self.bounds;
        _secondWaveShapeLayer.fillColor = _firstWaveColor.CGColor;
    }
    
    return _secondWaveShapeLayer;
}

-(UILabel *)progressLabel{
    if (!_progressLabel) {
        _progressLabel=[[UILabel alloc] init];
        _progressLabel.text=@"0%";
        _progressLabel.frame=CGRectMake(0, 0, self.bounds.size.width, 30);
        _progressLabel.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
        _progressLabel.font=[UIFont systemFontOfSize:20];
        _progressLabel.textColor=[UIColor colorWithWhite:0 alpha:1];
        _progressLabel.textAlignment=NSTextAlignmentCenter;
    }
    return _progressLabel;
}



-(void)dealloc{
    
    NSLog(@"释放了：%s",__FUNCTION__);
    
    [self.displayLinkTimer invalidate];
    self.displayLinkTimer = nil;
    
    if (_firstWaveShapeLayer) {
        [_firstWaveShapeLayer removeFromSuperlayer];
        _firstWaveShapeLayer = nil;
    }
    
    if (_secondWaveShapeLayer) {
        [_secondWaveShapeLayer removeFromSuperlayer];
        _secondWaveShapeLayer = nil;
    }
}

@end
